<template>
  <div class="course-detail-container">
    <!-- 课程头部信息 -->
    <div class="course-header">
      <div class="container">
        <div class="course-header-content">
          <div class="course-info">
            <div class="breadcrumb">
              <el-breadcrumb separator="/">
                <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
                <el-breadcrumb-item :to="{ path: '/classroom' }">智能课堂</el-breadcrumb-item>
                <el-breadcrumb-item>{{ course.title }}</el-breadcrumb-item>
              </el-breadcrumb>
            </div>
            
            <h1 class="course-title">{{ course.title }}</h1>
            <p class="course-subtitle">{{ course.subtitle }}</p>
            
            <div class="course-meta">
              <div class="meta-item">
                <el-icon><User /></el-icon>
                <span>{{ course.instructor }}</span>
              </div>
              <div class="meta-item">
                <el-icon><Clock /></el-icon>
                <span>{{ course.duration }}</span>
              </div>
              <div class="meta-item">
                <el-icon><Star /></el-icon>
                <span>{{ course.rating }}</span>
                <span class="rating-count">({{ course.ratingCount }}人评价)</span>
              </div>
              <div class="meta-item">
                <el-icon><UserFilled /></el-icon>
                <span>{{ formatNumber(course.studentCount) }}人学习</span>
              </div>
            </div>
            
            <div class="course-tags">
              <el-tag v-for="tag in course.tags" :key="tag" type="info">{{ tag }}</el-tag>
            </div>
            
            <div class="course-actions">
              <el-button 
                v-if="!isEnrolled" 
                type="primary" 
                size="large"
                @click="handleEnroll"
                :loading="enrollLoading"
              >
                {{ course.price > 0 ? `¥${course.price} 立即购买` : '免费学习' }}
              </el-button>
              <el-button 
                v-else
                type="success" 
                size="large"
                @click="continueLearning"
              >
                继续学习
              </el-button>
              <el-button 
                size="large"
                @click="handleFavorite"
                :icon="isFavorited ? 'StarFilled' : 'Star'"
              >
                {{ isFavorited ? '已收藏' : '收藏' }}
              </el-button>
            </div>
          </div>
          
          <div class="course-preview">
            <div class="video-container">
              <video 
                v-if="course.previewVideo"
                :src="course.previewVideo"
                :poster="course.cover"
                controls
                class="preview-video"
              >
                您的浏览器不支持视频播放
              </video>
              <img v-else :src="course.cover" :alt="course.title" class="course-cover" />
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 课程内容 -->
    <div class="course-content">
      <div class="container">
        <div class="content-layout">
          <!-- 主要内容 -->
          <div class="main-content">
            <el-tabs v-model="activeTab" class="course-tabs">
              <!-- 课程介绍 -->
              <el-tab-pane label="课程介绍" name="intro">
                <div class="course-intro">
                  <h3>课程简介</h3>
                  <div class="intro-content" v-html="course.description"></div>
                  
                  <h3>学习目标</h3>
                  <ul class="learning-goals">
                    <li v-for="goal in course.learningGoals" :key="goal">{{ goal }}</li>
                  </ul>
                  
                  <h3>适合人群</h3>
                  <ul class="target-audience">
                    <li v-for="audience in course.targetAudience" :key="audience">{{ audience }}</li>
                  </ul>
                </div>
              </el-tab-pane>
              
              <!-- 课程目录 -->
              <el-tab-pane label="课程目录" name="chapters">
                <div class="course-chapters">
                  <div class="chapters-header">
                    <h3>课程目录</h3>
                    <div class="chapters-stats">
                      <span>共{{ totalChapters }}章</span>
                      <span>{{ totalLessons }}节课</span>
                      <span>{{ totalDuration }}</span>
                    </div>
                  </div>
                  
                  <div class="chapters-list">
                    <div 
                      v-for="(chapter, index) in chapters" 
                      :key="chapter.id"
                      class="chapter-item"
                    >
                      <div class="chapter-header" @click="toggleChapter(index)">
                        <div class="chapter-info">
                          <el-icon>
                            <CaretRight v-if="!chapter.expanded" />
                            <CaretBottom v-else />
                          </el-icon>
                          <span class="chapter-title">第{{ index + 1 }}章 {{ chapter.title }}</span>
                          <span class="chapter-stats">{{ chapter.lessons.length }}节课</span>
                        </div>
                      </div>
                      
                      <div v-show="chapter.expanded" class="lessons-list">
                        <div 
                          v-for="(lesson, lessonIndex) in chapter.lessons"
                          :key="lesson.id"
                          class="lesson-item"
                          @click="playLesson(lesson)"
                        >
                          <div class="lesson-info">
                            <el-icon>
                              <VideoPlay v-if="lesson.type === 'video'" />
                              <Document v-else-if="lesson.type === 'document'" />
                              <EditPen v-else />
                            </el-icon>
                            <span class="lesson-title">{{ lessonIndex + 1 }}. {{ lesson.title }}</span>
                          </div>
                          <div class="lesson-meta">
                            <span class="lesson-duration">{{ lesson.duration }}</span>
                            <el-icon v-if="lesson.completed" class="completed-icon">
                              <CircleCheckFilled />
                            </el-icon>
                            <el-icon v-else-if="!isEnrolled" class="lock-icon">
                              <Lock />
                            </el-icon>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </el-tab-pane>
              
              <!-- 课程评价 -->
              <el-tab-pane label="课程评价" name="reviews">
                <div class="course-reviews">
                  <div class="reviews-summary">
                    <div class="rating-overview">
                      <div class="rating-score">{{ course.rating }}</div>
                      <div class="rating-stars">
                        <el-rate v-model="course.rating" disabled show-score />
                      </div>
                      <div class="rating-count">{{ course.ratingCount }}人评价</div>
                    </div>
                  </div>
                  
                  <div class="reviews-list">
                    <div 
                      v-for="review in reviews" 
                      :key="review.id"
                      class="review-item"
                    >
                      <div class="review-header">
                        <el-avatar :src="review.userAvatar">{{ review.userName.charAt(0) }}</el-avatar>
                        <div class="review-info">
                          <div class="user-name">{{ review.userName }}</div>
                          <div class="review-meta">
                            <el-rate v-model="review.rating" disabled size="small" />
                            <span class="review-date">{{ formatDate(review.createTime) }}</span>
                          </div>
                        </div>
                      </div>
                      <div class="review-content">{{ review.content }}</div>
                    </div>
                  </div>
                  
                  <div class="load-more" v-if="hasMoreReviews">
                    <el-button @click="loadMoreReviews" :loading="reviewsLoading">加载更多</el-button>
                  </div>
                </div>
              </el-tab-pane>
            </el-tabs>
          </div>
          
          <!-- 侧边栏 -->
          <div class="sidebar">
            <!-- 学习进度 -->
            <div v-if="isEnrolled" class="progress-card">
              <h4>学习进度</h4>
              <el-progress 
                :percentage="learningProgress" 
                :stroke-width="8"
                :show-text="true"
              />
              <div class="progress-stats">
                <span>已完成 {{ completedLessons }}/{{ totalLessons }} 节课</span>
              </div>
            </div>
            
            <!-- 讲师信息 -->
            <div class="instructor-card">
              <h4>讲师介绍</h4>
              <div class="instructor-info">
                <el-avatar :size="60" :src="instructor.avatar">
                  {{ instructor.name.charAt(0) }}
                </el-avatar>
                <div class="instructor-details">
                  <div class="instructor-name">{{ instructor.name }}</div>
                  <div class="instructor-title">{{ instructor.title }}</div>
                  <div class="instructor-stats">
                    <div>{{ instructor.courseCount }}门课程</div>
                    <div>{{ formatNumber(instructor.studentCount) }}名学员</div>
                  </div>
                </div>
              </div>
              <div class="instructor-bio">{{ instructor.bio }}</div>
            </div>
            
            <!-- 相关课程 -->
            <div class="related-courses">
              <h4>相关课程</h4>
              <div class="related-list">
                <div 
                  v-for="relatedCourse in relatedCourses" 
                  :key="relatedCourse.id"
                  class="related-item"
                  @click="viewCourse(relatedCourse.id)"
                >
                  <img :src="relatedCourse.cover" :alt="relatedCourse.title" />
                  <div class="related-info">
                    <div class="related-title">{{ relatedCourse.title }}</div>
                    <div class="related-price">
                      {{ relatedCourse.price > 0 ? `¥${relatedCourse.price}` : '免费' }}
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getCourseDetail, 
  getCourseChapters, 
  getCourseReviews,
  enrollCourse,
  checkEnrollment,
  favoriteCourse,
  unfavoriteCourse,
  getCourseProgress
} from '@/api/classroom'

const route = useRoute()
const router = useRouter()

const loading = ref(true)
const enrollLoading = ref(false)
const reviewsLoading = ref(false)
const activeTab = ref('intro')

const course = ref({})
const chapters = ref([])
const reviews = ref([])
const instructor = ref({})
const relatedCourses = ref([])

const isEnrolled = ref(false)
const isFavorited = ref(false)
const learningProgress = ref(0)
const completedLessons = ref(0)
const hasMoreReviews = ref(true)

// 计算属性
const totalChapters = computed(() => chapters.value.length)
const totalLessons = computed(() => {
  return chapters.value.reduce((total, chapter) => total + chapter.lessons.length, 0)
})
const totalDuration = computed(() => course.value.duration || '0小时')

// 获取课程详情
const getCourseInfo = async () => {
  loading.value = true
  try {
    const courseId = route.params.id
    const [courseRes, chaptersRes, enrollmentRes] = await Promise.all([
      getCourseDetail(courseId),
      getCourseChapters(courseId),
      checkEnrollment(courseId)
    ])
    
    if (courseRes.code === 200) {
      course.value = courseRes.data
      instructor.value = courseRes.data.instructor || {}
    }
    
    if (chaptersRes.code === 200) {
      chapters.value = chaptersRes.data.map(chapter => ({
        ...chapter,
        expanded: false
      }))
    }
    
    if (enrollmentRes.code === 200) {
      isEnrolled.value = enrollmentRes.data.enrolled
      if (isEnrolled.value) {
        getProgress()
      }
    }
    
    getReviews()
  } catch (error) {
    console.error('获取课程信息失败:', error)
    ElMessage.error('获取课程信息失败')
  } finally {
    loading.value = false
  }
}

// 获取学习进度
const getProgress = async () => {
  try {
    const response = await getCourseProgress(route.params.id)
    if (response.code === 200) {
      learningProgress.value = response.data.progress
      completedLessons.value = response.data.completedLessons
    }
  } catch (error) {
    console.error('获取学习进度失败:', error)
  }
}

// 获取课程评价
const getReviews = async () => {
  try {
    const response = await getCourseReviews(route.params.id, { pageNum: 1, pageSize: 10 })
    if (response.code === 200) {
      reviews.value = response.data.records || []
      hasMoreReviews.value = response.data.hasNext
    }
  } catch (error) {
    console.error('获取课程评价失败:', error)
  }
}

// 报名课程
const handleEnroll = async () => {
  enrollLoading.value = true
  try {
    if (course.value.price > 0) {
      // 付费课程，跳转到支付页面
      router.push(`/payment/course/${route.params.id}`)
    } else {
      // 免费课程，直接报名
      await enrollCourse(route.params.id)
      isEnrolled.value = true
      ElMessage.success('报名成功！')
    }
  } catch (error) {
    console.error('报名失败:', error)
    ElMessage.error('报名失败')
  } finally {
    enrollLoading.value = false
  }
}

// 收藏课程
const handleFavorite = async () => {
  try {
    if (isFavorited.value) {
      await unfavoriteCourse(route.params.id)
      isFavorited.value = false
      ElMessage.success('取消收藏成功')
    } else {
      await favoriteCourse(route.params.id)
      isFavorited.value = true
      ElMessage.success('收藏成功')
    }
  } catch (error) {
    console.error('收藏操作失败:', error)
    ElMessage.error('操作失败')
  }
}

// 继续学习
const continueLearning = () => {
  // 跳转到学习页面
  router.push(`/classroom/learn/${route.params.id}`)
}

// 切换章节展开状态
const toggleChapter = (index) => {
  chapters.value[index].expanded = !chapters.value[index].expanded
}

// 播放课时
const playLesson = (lesson) => {
  if (!isEnrolled.value) {
    ElMessage.warning('请先报名课程')
    return
  }
  router.push(`/classroom/learn/${route.params.id}/lesson/${lesson.id}`)
}

// 查看其他课程
const viewCourse = (courseId) => {
  router.push(`/classroom/course/${courseId}`)
}

// 格式化数字
const formatNumber = (num) => {
  if (num >= 10000) {
    return (num / 10000).toFixed(1) + '万'
  }
  return num.toLocaleString()
}

// 格式化日期
const formatDate = (date) => {
  return new Date(date).toLocaleDateString()
}

// 加载更多评价
const loadMoreReviews = async () => {
  reviewsLoading.value = true
  try {
    const response = await getCourseReviews(route.params.id, { 
      pageNum: Math.floor(reviews.value.length / 10) + 1, 
      pageSize: 10 
    })
    if (response.code === 200) {
      reviews.value.push(...response.data.records)
      hasMoreReviews.value = response.data.hasNext
    }
  } catch (error) {
    console.error('加载评价失败:', error)
  } finally {
    reviewsLoading.value = false
  }
}

onMounted(() => {
  getCourseInfo()
})
</script>

<style lang="scss" scoped>
.course-detail-container {
  min-height: 100vh;
  background: var(--el-bg-color-page);
}

.course-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 40px 0;
}

.course-header-content {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 40px;
  align-items: start;
  
  @media (max-width: 768px) {
    grid-template-columns: 1fr;
  }
}

.breadcrumb {
  margin-bottom: 20px;
  
  :deep(.el-breadcrumb__inner) {
    color: rgba(255, 255, 255, 0.8);
    
    &:hover {
      color: white;
    }
  }
}

.course-title {
  font-size: 2.5rem;
  font-weight: 700;
  margin-bottom: 12px;
}

.course-subtitle {
  font-size: 1.25rem;
  opacity: 0.9;
  margin-bottom: 24px;
}

.course-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 24px;
  margin-bottom: 20px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
}

.course-tags {
  margin-bottom: 32px;
  
  .el-tag {
    margin-right: 8px;
    margin-bottom: 8px;
  }
}

.course-actions {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
}

.video-container {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
}

.preview-video,
.course-cover {
  width: 100%;
  height: auto;
  display: block;
}

.course-content {
  padding: 40px 0;
}

.content-layout {
  display: grid;
  grid-template-columns: 1fr 300px;
  gap: 40px;
  
  @media (max-width: 768px) {
    grid-template-columns: 1fr;
  }
}

.course-tabs {
  :deep(.el-tabs__header) {
    margin-bottom: 24px;
  }
}

.course-intro {
  h3 {
    font-size: 1.25rem;
    font-weight: 600;
    margin-bottom: 16px;
    margin-top: 32px;
    
    &:first-child {
      margin-top: 0;
    }
  }
  
  .intro-content {
    line-height: 1.6;
    margin-bottom: 24px;
  }
  
  ul {
    padding-left: 20px;
    
    li {
      margin-bottom: 8px;
      line-height: 1.6;
    }
  }
}

.chapters-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  
  h3 {
    font-size: 1.25rem;
    font-weight: 600;
  }
  
  .chapters-stats {
    display: flex;
    gap: 16px;
    font-size: 14px;
    color: var(--el-text-color-secondary);
  }
}

.chapter-item {
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 8px;
  margin-bottom: 12px;
  overflow: hidden;
}

.chapter-header {
  padding: 16px;
  background: var(--el-bg-color-light);
  cursor: pointer;
  
  &:hover {
    background: var(--el-fill-color-light);
  }
}

.chapter-info {
  display: flex;
  align-items: center;
  gap: 12px;
  
  .chapter-title {
    font-weight: 600;
    flex: 1;
  }
  
  .chapter-stats {
    font-size: 14px;
    color: var(--el-text-color-secondary);
  }
}

.lessons-list {
  border-top: 1px solid var(--el-border-color-lighter);
}

.lesson-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  cursor: pointer;
  
  &:hover {
    background: var(--el-fill-color-light);
  }
  
  &:not(:last-child) {
    border-bottom: 1px solid var(--el-border-color-lighter);
  }
}

.lesson-info {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
}

.lesson-meta {
  display: flex;
  align-items: center;
  gap: 8px;
  
  .lesson-duration {
    font-size: 14px;
    color: var(--el-text-color-secondary);
  }
  
  .completed-icon {
    color: var(--el-color-success);
  }
  
  .lock-icon {
    color: var(--el-text-color-disabled);
  }
}

.sidebar {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.progress-card,
.instructor-card,
.related-courses {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  
  h4 {
    font-size: 1.125rem;
    font-weight: 600;
    margin-bottom: 16px;
  }
}

.progress-stats {
  margin-top: 12px;
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

.instructor-info {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
}

.instructor-details {
  flex: 1;
  
  .instructor-name {
    font-weight: 600;
    margin-bottom: 4px;
  }
  
  .instructor-title {
    font-size: 14px;
    color: var(--el-text-color-secondary);
    margin-bottom: 8px;
  }
  
  .instructor-stats {
    display: flex;
    gap: 16px;
    font-size: 14px;
    color: var(--el-text-color-secondary);
  }
}

.instructor-bio {
  font-size: 14px;
  line-height: 1.6;
  color: var(--el-text-color-regular);
}

.related-item {
  display: flex;
  gap: 12px;
  padding: 12px 0;
  cursor: pointer;
  
  &:hover {
    .related-title {
      color: var(--el-color-primary);
    }
  }
  
  &:not(:last-child) {
    border-bottom: 1px solid var(--el-border-color-lighter);
  }
  
  img {
    width: 60px;
    height: 40px;
    border-radius: 4px;
    object-fit: cover;
  }
}

.related-info {
  flex: 1;
  
  .related-title {
    font-size: 14px;
    font-weight: 500;
    margin-bottom: 4px;
    @include text-ellipsis(2);
  }
  
  .related-price {
    font-size: 14px;
    color: var(--el-color-danger);
    font-weight: 600;
  }
}

.reviews-summary {
  margin-bottom: 32px;
}

.rating-overview {
  display: flex;
  align-items: center;
  gap: 24px;
  
  .rating-score {
    font-size: 3rem;
    font-weight: 700;
    color: var(--el-color-warning);
  }
  
  .rating-stars {
    display: flex;
    flex-direction: column;
    gap: 8px;
  }
  
  .rating-count {
    font-size: 14px;
    color: var(--el-text-color-secondary);
  }
}

.review-item {
  padding: 24px 0;
  border-bottom: 1px solid var(--el-border-color-lighter);
  
  &:last-child {
    border-bottom: none;
  }
}

.review-header {
  display: flex;
  gap: 16px;
  margin-bottom: 12px;
}

.review-info {
  flex: 1;
  
  .user-name {
    font-weight: 600;
    margin-bottom: 4px;
  }
  
  .review-meta {
    display: flex;
    align-items: center;
    gap: 12px;
    
    .review-date {
      font-size: 14px;
      color: var(--el-text-color-secondary);
    }
  }
}

.review-content {
  line-height: 1.6;
  color: var(--el-text-color-regular);
}

.load-more {
  text-align: center;
  margin-top: 24px;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}
</style>
